"use client";
import { useCart } from '@/contexts/CartContext';
import { toast } from "sonner";
import { useState, useEffect, useCallback } from "react";
import Image from "next/image";
import { useParams } from "next/navigation";
import { Product } from '@/types/Product';
import { Review } from '@/types/Review';
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { useAuth } from '@/contexts/AuthContext';
import { PageBackground } from '@/components/ui/page-background';
import { Slider } from '@/components/ui/slider';
import { Label } from '@/components/ui/label';
import { useUIPreferences } from '@/contexts/UIPreferencesContext';

import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { addReview, getReviews, getProductById } from "@/lib/api";

const formSchema = z.object({
  rating: z.coerce.number().min(1, {message: "评分必须在1-5之间"}).max(5, {message: "评分必须在1-5之间"}),
  comment: z.string().min(10, { message: "评价内容不能少于10个字符。" }),
});

export default function ProductDetailPage() {
  const params = useParams();
  const productId = params.productId as string;
  const { isAuthenticated, user } = useAuth();
  const username = user?.username;
  const { getOpacity, setOpacity } = useUIPreferences();
  const productPageOpacity = getOpacity('product');
  const { addToCart } = useCart();
  const [quantity, setQuantity] = useState(1);
  const [isAdding, setIsAdding] = useState(false);

  const [product, setProduct] = useState<Product | null>(null);
  const [reviews, setReviews] = useState<Review[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      rating: 5,
      comment: "",
    },
  });

  const { isSubmitting: formIsSubmitting } = form.formState;

  const fetchProductAndReviews = useCallback(async () => {
    if (!productId) return;
    try {
      setError(null);
      const [fetchedProduct, fetchedReviews] = await Promise.all([
        getProductById(productId),
        getReviews(productId)
      ]);
      setProduct(fetchedProduct);
      setReviews(fetchedReviews);
    } catch (err) {
      console.error("Failed to fetch product or reviews:", err);
      setError("无法加载商品或评价，请稍后重试。");
    }
  }, [productId]);

  useEffect(() => {
    fetchProductAndReviews();
  }, [fetchProductAndReviews]);

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (form.getValues('rating') < 1 || form.getValues('rating') > 5) {
      alert("评分必须在 1 到 5 之间。");
      return;
    }
    setIsSubmitting(true);
    setError(null);

    const newReviewData: Omit<Review, 'rowKey' | 'reviewDate'> = {
      rating: form.getValues('rating'),
      comment: form.getValues('comment'),
      productId: product?.id || '',
      userId: username || '',
      userName: username || '',
      productName: product?.name || '',
      productCategory: product?.category || '',
    };

    try {
      await addReview(newReviewData);
      await fetchProductAndReviews();
      form.reset({ rating: 0, comment: "" });
    } catch (error) {
      console.error("Failed to submit review", error);
      setError("提交评价失败，请检查网络连接或稍后重试。");
    } finally {
      setIsSubmitting(false);
    }
  };
  
  const handleAddToCart = async () => {
    if (!product) return;
    setIsAdding(true);
    try {
      await addToCart(product, quantity);
      toast.success(`${product.name} 已添加到购物车!`);
    } catch (error) {
      toast.error("添加失败，请稍后重试。");
      console.error(error);
    } finally {
      setIsAdding(false);
    }
  };
  
  if (error && !product) {
      return (
        <div className="container mx-auto p-4 text-center">
            <p className="text-destructive">{error}</p>
        </div>
      )
  }

  if (!product) {
    return (
        <div className="container mx-auto p-4 text-center">
            <p>正在加载商品...</p>
        </div>
    )
  }

  return (
    <>
      <PageBackground src={product.imageUrl} opacity={productPageOpacity} />

      <div className="fixed bottom-4 right-4 z-50 w-48 rounded-lg border bg-background/80 p-4 shadow-lg backdrop-blur-sm">
        <label htmlFor="opacity-slider" className="mb-2 block text-sm font-medium">
          背景不透明度
        </label>
        <Slider
          id="opacity-slider"
          min={0}
          max={1}
          step={0.05}
          value={[productPageOpacity]}
          onValueChange={(value) => setOpacity('product', value[0])}
        />
      </div>

      <div className="container mx-auto max-w-6xl px-4 py-8 relative z-10">
        <div className="grid md:grid-cols-2 gap-8 lg:gap-12 items-start">
          <Card className="bg-background/80 backdrop-blur-sm">
            <CardContent className="p-0">
              <Image
                src={product.imageUrl}
                alt={product.name}
                width={600}
                height={600}
                className="w-full h-auto rounded-lg object-cover"
              />
            </CardContent>
          </Card>
          <div className="flex flex-col gap-6">
            <Card className="bg-background/80 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="text-3xl font-bold">{product.name}</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-muted-foreground">{product.description}</p>
                {product.price && (
                  <div className="mt-4 text-3xl font-bold text-cyan-400">
                    ¥{product.price.toFixed(2)}
                  </div>
                )}
                
                <div className="mt-6 flex items-center gap-4">
                  <Input 
                    type="number"
                    value={quantity}
                    onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value) || 1))}
                    className="w-20"
                    min="1"
                  />
                  <Button onClick={handleAddToCart} disabled={isAdding || !isAuthenticated} className="flex-grow">
                    {isAdding ? '添加中...' : '加入购物车'}
                  </Button>
                </div>
                {!isAuthenticated && <p className="text-sm text-yellow-500 mt-2">请登录后添加到购物车</p>}

              </CardContent>
            </Card>

            <Card className="bg-background/80 backdrop-blur-sm">
              <CardHeader>
                <CardTitle>评价</CardTitle>
              </CardHeader>
              <CardContent>
              {error && <p className="text-sm text-destructive mb-4">{error}</p>}
                <div className="space-y-4">
                  {reviews.length > 0 ? reviews.map((review) => (
                    <div key={review.rowKey} className="border-b pb-4 last:border-b-0">
                      <div className="flex items-center justify-between">
                        <p className="font-semibold">{review.userName}</p>
                        <p className="text-sm text-muted-foreground">{Array(review.rating).fill('⭐').join('')}</p>
                      </div>
                      <p className="mt-2 text-sm text-muted-foreground">{review.comment}</p>
                    </div>
                  )) : <p className="text-sm text-muted-foreground">暂无评价，快来成为第一个评价的人吧！</p>}
                </div>
              </CardContent>
            </Card>

            {isAuthenticated && (
              <Card className="bg-background/80 backdrop-blur-sm">
                <CardHeader>
                  <CardTitle>发表您的评价</CardTitle>
                </CardHeader>
                <CardContent>
                  <Form {...form}>
                    <form onSubmit={onSubmit} className="space-y-8">
                      <FormField control={form.control} name="rating" render={({ field }) => (
                        <FormItem>
                          <FormLabel>评分 (1-5)</FormLabel>
                          <FormControl><Input type="number" min="1" max="5" {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="comment" render={({ field }) => (
                        <FormItem>
                          <FormLabel>评价内容</FormLabel>
                          <FormControl><Textarea placeholder="分享您的使用体验..." {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <Button type="submit" disabled={formIsSubmitting}>
                        {formIsSubmitting ? '正在提交...' : '提交评价'}
                      </Button>
                    </form>
                    {error && <p className="mt-4 text-sm font-medium text-destructive">{error}</p>}
                  </Form>
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </div>
    </>
  );
} 